package com.hollycrm.unicom.sheet.code;

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hollycrm.springframework.cache.Cache;
import com.hollycrm.springframework.cache.CacheException;
import com.hollycrm.springframework.cache.CacheFactory;
import com.hollycrm.springframework.factory.DefaultBeanFactory;

/**
 * CleanCacheCodeJob
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author Tian Kai
 * @version 1.0
 */
public class CleanCacheCodeJob {

  protected Log logger = LogFactory.getLog(getClass());

  protected Properties regionProps;

  /**
   * CleanCacheCodeJob
   */
  public CleanCacheCodeJob() {

  }

  /**
   * CleanCacheCodeJob
   *
   * @param regionProps Properties
   */
  public CleanCacheCodeJob(Properties regionProps) {
    this.regionProps = regionProps;
  }

  /**
   * execute
   */
  public void execute() {
    Set keySet = regionProps.keySet();
    for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
      try {
        String regionName = ( (String) regionProps.getProperty( (String)
            iter.next()));
        Cache cache = getCache(regionName);
        //test
        logger.info("[cleanCache:]" + regionName);

        cache.clear();
      }
      catch (CacheException ex) {
        logger.warn("[w] " + ex.getMessage());
      }
    }
  }

  /**
   * getCache
   *
   * @param regionName String
   * @throws CacheException
   * @return Cache
   */
  protected static Cache getCache(String regionName) throws CacheException {
    return ( (CacheFactory) DefaultBeanFactory.getBean(CacheFactory.BEAN_ID)).
        buildCache(regionName);
  }
  /**
   * cleanSeperateCache
   *
   * @param regionName String
   * @throws CacheException
   * @return
   */
  public void cleanSeperateCache(String regionName) throws CacheException {
    try{
      Cache cache = getCache(regionName);
      cache.clear();
    }catch(CacheException ex){
      logger.warn("[cleanCache failed:] "+ regionName + ex.getMessage());
    }
  }

}